package controller

import (
	"strconv"

	"core/api/controller/response"

	"core/service"

	"github.com/gin-gonic/gin"
)

func findProjectGroupPage(c *gin.Context) {
	projectGroups, err := service.ListProjectGroups()
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, projectGroups)
}

func findProjectPage(c *gin.Context) {
	pageNum, err := strconv.Atoi(c.Query("pageNum"))
	if err != nil {
		SendError(c, err)
		return
	}

	pageSize, err := strconv.Atoi(c.Query("pageSize"))
	if err != nil {
		SendError(c, err)
		return
	}

	projectGroupId := c.Query("projectGroupId")

	projects, err := service.ListProjects(pageNum, pageSize, projectGroupId)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, response.PageResponse{List: projects})
}

func findNodePage(c *gin.Context) {
	pageNum, err := strconv.Atoi(c.Query("pageNum"))
	if err != nil {
		SendError(c, err)
		return
	}

	pageSize, err := strconv.Atoi(c.Query("pageSize"))
	if err != nil {
		SendError(c, err)
		return
	}

	response, err := service.ListHubNodeDefinitions(pageNum, pageSize)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, response)
}

func findNamespace(c *gin.Context) {
	namespaces, err := service.ListNamespaces()
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, response.NamespaceResponse{List: namespaces, CredentialManagerType: "local"})
}

func findNamespaceByName(c *gin.Context) {
	name := c.Param("name")

	namespaces, err := service.FindNamespaceByName(name)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, namespaces)
}

func findNamespaceKeyByName(c *gin.Context) {
	name := c.Param("name")
	keys, err := service.FindNamespaceKeyByName(name)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, keys)
}

func findWorkflowVersion(c *gin.Context) {
	workflowRef := c.Param("workflowRef")
	workflowVersion := c.Param("workflowVersion")

	workflow, err := service.FindWorkflowByRefAndVersion(workflowRef, workflowVersion)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, workflow)
}

func findProjectById(c *gin.Context) {
	projectId := c.Param("projectId")
	project, err := service.FindProjectById(projectId)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, project)
}

func ViewRegister(r *gin.Engine) {
	r.GET("/view/projects/groups", findProjectGroupPage)
	r.GET("/view/nodes", findNodePage)
	r.GET("/view/v2/projects", findProjectPage)
	r.GET("/view/namespaces", findNamespace)
	r.GET("/view/namespaces/:name", findNamespaceByName)
	r.GET("/view/namespaces/:name/keys", findNamespaceKeyByName)
	r.GET("/view/workflow/:workflowRef/:workflowVersion", findWorkflowVersion)
	r.GET("/view/projects/:projectId", findProjectById)
}
